package com.atguigu.daijia.customer.interceptor;

import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.common.util.AuthContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author 山顶洞人郑某
 * @className CustomerlerInterceptor.java 用户消费者自定义拦截器
 * @date 2024 09 05
 */
@Component
@Slf4j
public class CustomerlerInterceptor implements HandlerInterceptor {
    private final StringRedisTemplate stringRedisTemplate;

    public CustomerlerInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (!Optional.ofNullable(token).isPresent()) {
            throw new GuiguException(ResultCodeEnum.FAIL);
        }
        String key = RedisConstant.USER_LOGIN_KEY_PREFIX+token;
        String userId = stringRedisTemplate.opsForValue().get(key);
        if (!Optional.ofNullable(userId).isPresent()) {
            throw new GuiguException(ResultCodeEnum.NOT_LOGIN);
        }
        //TODO:查询数据库是否有用户信息
        //刷新用户登录时间状态
        stringRedisTemplate.opsForValue().set(key,userId,RedisConstant.USER_LOGIN_REFRESH_KEY_TIMEOUT, TimeUnit.MINUTES);
        AuthContextHolder.setUserId(Long.valueOf(userId));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
      AuthContextHolder.removeUserId();
    }
}
